package cn.sangedon.review.data.spider.impl;

import cn.hutool.http.HttpRequest;
import cn.sangedon.review.common.domain.data.SpiderMateData;
import cn.sangedon.review.common.domain.data.TradingDate;
import cn.sangedon.review.common.service.data.TradingDateService;
import cn.sangedon.review.data.constant.SpiderEnum;
import cn.sangedon.review.data.spider.AbstractStockInfoSpider;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 股票交易日历获取
 * 从深圳交易所获取
 *
 * @author dongliangqiong
 */
@Slf4j
@Component
public class TradeCalendarSpider extends AbstractStockInfoSpider {
    @Autowired
    private TradingDateService tradingDateService;

    @Override
    public void runJob(List<SpiderMateData> spiderMateDataList) {
        spiderMateDataList.stream().filter(e -> e.getSpiderName().equals(SpiderEnum.TRADE_DATE.getName())).findFirst().ifPresent(e -> {
            addSchedule(e);
        });
    }

    @Override
    public void crawlData() {
        AtomicInteger index = new AtomicInteger(0);
        while (!processData() && index.getAndIncrement() < 3) {
            log.info("重试获取交易日历数据{}次", index.intValue());
        }
    }

    private boolean processData() {
        try {
            log.info("开始获取交易日历数据");
            DateFormat df = new SimpleDateFormat("yyyy-MM");
            String spiderUrl = String.format(getSpiderMateData().getSpiderUrl(), df.format(new Date()));
            String body = HttpRequest.get(spiderUrl).execute().body();
            JSONObject result = JSONObject.parseObject(body);
            List<TradingDate> list = new ArrayList<>();
            JSONArray data = result.getJSONArray("data");
            for (Object datum : data) {
                JSONObject dateObj = (JSONObject) datum;
                if (!dateObj.getString("jybz").equals("1")) {
                    continue;
                }
                TradingDate tradingDate = new TradingDate();
                tradingDate.setTradingDate(dateObj.getString("jyrq"));
                tradingDate.setWeekDay(dateObj.getInteger("zrxh"));
                list.add(tradingDate);
            }
            tradingDateService.saveOrUpdateBatch(list);
            log.info("交易日历数据保存成功:{}", list.size());
            return true;
        } catch (Exception e) {
            log.error("获取交易日历数据失败:{}", e);
            return false;
        }
    }
}
